package com.bl.weilan.service.biz.company.impl;

import com.bl.weilan.common.ApiResponseCode;
import com.bl.weilan.common.CommonServiceException;
import com.bl.weilan.common.utils.ListUtils;
import com.bl.weilan.common.utils.UUIDUtils;
import com.bl.weilan.dao.model.*;
import com.bl.weilan.dao.repository.*;
import com.bl.weilan.service.biz.company.CompanyService;
import com.bl.weilan.service.biz.companyfinancing.CompanyFinancingService;
import com.bl.weilan.service.biz.companyinvester.CompanyInvesterService;
import com.bl.weilan.service.vo.DelBody;
import com.bl.weilan.service.vo.DelListBody;
import com.bl.weilan.service.vo.company.*;
import com.bl.weilan.service.vo.companyopponent.CompanyOpponentVo;
import com.bl.weilan.service.vo.companystockholder.CompanyStockholderVo;
import com.bl.weilan.service.vo.institution.InstitutionTeamVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


@Service
@Log4j2
public class CompanyServiceImpl implements CompanyService {
    @Autowired
    CompanyRepository companyRepository;
    @Autowired
    TradeARepository tradeARepository;
    @Autowired
    TradeBRepository tradeBRepository;
    @Autowired
    TradeCRepository tradeCRepository;
    @Autowired
    CompanyInvesterRepository companyInvesterRepository;
    @Autowired
    CompanyFinancingRepository companyFinancingRepository;
    @Autowired
    CompanyStockholderRepository companyStockholderRepository;
    @Autowired
    CompanyPointRepository companyPointRepository;
    @Autowired
    CompanyReportRepository companyReportRepository;
    @Autowired
    CompanyOpponentRepository companyOpponentRepository;
    @Autowired
    CompanyModelRepository companyModelRepository;
    @Autowired
    CompanyTeamRepository companyTeamRepository;
    @Autowired
    InstitutionCompanyRepository institutionCompanyRepository;
    @Autowired
    InstitutionRepository institutionRepository;
    @Autowired
    CompanyTradeRepository companyTradeRepository;
    @Autowired
    CompanyFinancingService companyFinancingService;
    @Autowired
    PeopleRepository peopleRepository;

    @Autowired
    TradeChartRepository tradeChartRepository;
    @Autowired
    TradeChartDetailRepository tradeChartDetailRepository;

    @Autowired
    CompanyInvesterService companyInvesterService;

    @Override
    public CompanyVo getCompanyById(String companyId) {
        CompanyVo companyVo = new CompanyVo();
        CompanyEntity companyEntity = companyRepository.findOne(companyId);
        BeanUtils.copyProperties(companyEntity, companyVo);

        // 行业分类列表
        List<CompanyTradeEntity> companyTradeEntityList = new ArrayList<>();
        companyTradeEntityList = companyTradeRepository.findByCompanyId(companyId);
        companyVo.setCompanyTradeEntityList(companyTradeEntityList);

        // 行业路径
        List<String> tradePaths = new ArrayList<>();
        for(CompanyTradeEntity companyTradeEntity : companyTradeEntityList) {
            String tradePath = "";
            tradePath = companyTradeEntity.getTradeCName();
            tradePaths.add(tradePath);
        }
        companyVo.setTradePath(tradePaths);

////一级分类
//        String tradeAId = companyEntity.getTradeA();
//        TradeAEntity tradeAEntity  = new TradeAEntity();
//        tradeAEntity= tradeARepository.findOne(tradeAId);
//        companyVo.setTradeA(tradeAEntity.getName());
////二级分类
//        String tradeBId = companyEntity.getTradeB();
//        TradeBEntity tradeBEntity  = new TradeBEntity();
//        tradeBEntity= tradeBRepository.findOne(tradeBId);
//        companyVo.setTradeB(tradeBEntity.getName());
////三级分类
//        String tradeCId = companyEntity.getTradeC();
//        TradeCEntity tradeCEntity  = new TradeCEntity();
//        tradeCEntity= tradeCRepository.findOne(tradeCId);
//        companyVo.setTradeC(tradeCEntity.getName());

//        对外投资
        List<CompanyInvesterEntity> companyInvesterEntities;
        companyInvesterEntities = companyInvesterRepository.findByCompanyId(companyId);
        if (companyInvesterEntities != null){
            companyVo.setInvesterList(companyInvesterEntities);
        }
//      融资轮次
        List<CompanyFinancingEntity> companyFinancingEntities;
        companyFinancingEntities = companyFinancingRepository.findByCompanyId(companyId);
        if (companyFinancingEntities != null){
            companyVo.setFinancList(companyFinancingEntities);
        }
//      股东信息
        List<CompanyStockholderVo> companyStockholderVos = new ArrayList<>();
        List<CompanyStockholderEntity> coompanyStockholderEntities = companyStockholderRepository.findByCompanyIdOrderByWeightDesc(companyId);
        for (CompanyStockholderEntity companyStockholderEntity : coompanyStockholderEntities) {
            CompanyStockholderVo companyStockholderVo = new CompanyStockholderVo();
            BeanUtils.copyProperties(companyStockholderEntity, companyStockholderVo);
            PeopleEntity peopleEntity = peopleRepository.findOne(companyStockholderEntity.getPeopleId());
            companyStockholderVo.setPeopleName(peopleEntity.getName());
            companyStockholderVos.add(companyStockholderVo);
        }

        // 法人信息
        PeopleEntity corporate = peopleRepository.findOne(companyEntity.getCorporateId());
        companyVo.setCorporateName(corporate.getName());

        if (coompanyStockholderEntities != null){
            companyVo.setStockholderList(companyStockholderVos);
        }
//        综合评分
        List<CompanyPointEntity> companyPointEntities;
        companyPointEntities = companyPointRepository.findByCompanyId(companyId);
        if (companyPointEntities != null){
            companyVo.setPointList(companyPointEntities);
        }
//        新闻报道
        List<CompanyReportEntity> companyReportEntities;
        companyReportEntities = companyReportRepository.findByCompanyId(companyId);
        if (companyReportEntities != null){
            companyVo.setReportList(companyReportEntities);
        }
//      商业模式
        List<CompanyModelEntity> companyModelEntities;
        companyModelEntities = companyModelRepository.findByCompanyId(companyId);
        if (companyModelEntities != null){
            companyVo.setModelList(companyModelEntities);
        }
        // 管理团队
        List<CompanyTeamVo> institutionTeamVos = new ArrayList<>();
        List<CompanyTeamEntity> companyTeamEntities = companyTeamRepository.findByCompanyIdOrderByWeightDesc(companyId);
        for (CompanyTeamEntity companyTeamEntity : companyTeamEntities) {
            CompanyTeamVo companyTeamVo = new CompanyTeamVo();
            BeanUtils.copyProperties(companyTeamEntity, companyTeamVo);
            PeopleEntity peopleEntity = peopleRepository.findOne(companyTeamEntity.getPeopleId());
            companyTeamVo.setName(peopleEntity.getName());
            institutionTeamVos.add(companyTeamVo);
        }
        companyVo.setTeamList(institutionTeamVos);
//      公司相关机构列表
        List<InstitutionEntity> institutionEntities = new ArrayList<>();
        List<InstitutionCompanyEntity> institutionCompanyEntities;
        institutionCompanyEntities = institutionCompanyRepository.findByCompanyId(companyId);
        if (institutionCompanyEntities != null){
            for (InstitutionCompanyEntity isncompyEntity : institutionCompanyEntities){
                InstitutionEntity institutionEntity = new InstitutionEntity();
                String institutionId = isncompyEntity.getInstitutionId();
                institutionEntity = institutionRepository.findOne(institutionId);
                institutionEntities.add(institutionEntity);
            }
            companyVo.setInstitutionList(institutionEntities);
        }

        // 竞争对手
        List<CompanyOpponentVo> companyOpponentVos = new ArrayList<>();

        List<CompanyOpponentEntity>  companyOpponentEntityList = new ArrayList<>();
        companyOpponentEntityList = companyOpponentRepository.findByCompanyId(companyId);
        for (CompanyOpponentEntity companyOpponentEntity : companyOpponentEntityList) {

            List<CompanyOpponentEntity> companyOpponentEntities;
            String tradeDId = companyOpponentEntity.getTradeDId();

            companyOpponentEntities = companyOpponentRepository.findByTradeDId(tradeDId);
            if (null !=companyOpponentEntities && companyOpponentEntities.size() > 0){
                for (CompanyOpponentEntity opEntity : companyOpponentEntities) {
                    String compid = opEntity.getCompanyId();
                    if(compid.equals(companyId)) {
                        continue;
                    }else {
                        CompanyEntity companyEntity1 = companyRepository.findOne(opEntity.getCompanyId());
                        CompanyOpponentVo companyOpponentVo = new CompanyOpponentVo();
                        BeanUtils.copyProperties(companyEntity1, companyOpponentVo);
                        List<CompanyFinancingEntity> companyFinancingEntityList;
                        companyFinancingEntityList = companyFinancingRepository.findByCompanyIdOrderByTimeDesc(opEntity.getCompanyId());
                        if (companyFinancingEntityList != null){
                            companyOpponentVo.setFinancList(ListUtils.getFirst(companyFinancingEntityList));
                        }
                        companyOpponentVos.add(companyOpponentVo);
                    }
                }
            }
        }

        companyVo.setOpponentList(companyOpponentVos);

        return companyVo;
    }

    @Override
    public CompanyListVo getCompanyLists(Pageable pageable){
        CompanyListVo companyListVo = new CompanyListVo();
        List<CompanyVo> companyVos = new ArrayList<>();
        Page<CompanyEntity> companyEntities;

        companyEntities = companyRepository.findByOrderByWeightDesc(pageable);
        companyListVo.setTotalCount(companyEntities.getTotalElements());

        for (CompanyEntity companyEntity : companyEntities) {
            CompanyVo companyVo = new CompanyVo();
            String companyId = companyEntity.getId();
            companyVo = this.getCompanyById(companyId);
            companyVos.add(companyVo);
        }

        companyListVo.setList(companyVos);
        return companyListVo;
    }

    @Override
    public CompanyListVo getCompanyListsByTrade(String tradeId, String tradeType,  String type, String order, Pageable pageable){

        CompanyListVo companyListVo = new CompanyListVo();

//        Page<CompanyTradeEntity> companyTradeEntities = null;

//        if (tradeType.equals("TRADEB")) {
//            companyTradeEntities = companyTradeRepository.findByTradeB(tradeId, pageable);
//        } else if (tradeType.equals("TRADEC")) {
//            companyTradeEntities = companyTradeRepository.findByTradeC(tradeId, pageable);
//        }
//        if (companyTradeEntities == null){
//            return companyListVo;
//        } else {
//            List<CompanyVo> companyVos = new ArrayList<>();
//            for (CompanyTradeEntity companyTradeEntity : companyTradeEntities) {
//                CompanyEntity companyEntity = companyRepository.findOne(companyTradeEntity.getCompanyId());
//                CompanyVo companyVo = new CompanyVo();
//                String companyId = companyEntity.getId();
//                companyVo = this.getCompanyById(companyId);
//                PeopleEntity peopleEntity = peopleRepository.findOne(companyEntity.getCorporateId());
//                companyVo.setCorporateName(peopleEntity.getName());
//                companyVos.add(companyVo);
//            }
//            companyListVo.setTotalCount(companyTradeEntities.getTotalElements());
//            companyListVo.setList(companyVos);
//            return companyListVo;
//        }
        List<CompanyTradeEntity> companyTradeEntities = new ArrayList<>();
        List<CompanyVo> companyVos = new ArrayList<>();
        if (tradeType.equals("TRADEB")) {
            companyTradeEntities = companyTradeRepository.findByTradeB(tradeId);
        } else if (tradeType.equals("TRADEC")) {
            companyTradeEntities = companyTradeRepository.findByTradeC(tradeId);
        }
        if (companyTradeEntities == null){
            return companyListVo;
        } else {

            for (CompanyTradeEntity companyTradeEntity : companyTradeEntities) {
                CompanyEntity companyEntity = companyRepository.findOne(companyTradeEntity.getCompanyId());
                CompanyVo companyVo = new CompanyVo();
                String companyId = companyEntity.getId();
                companyVo = getCompanyById(companyId);
                PeopleEntity peopleEntity = peopleRepository.findOne(companyEntity.getCorporateId());
                companyVo.setCorporateName(peopleEntity.getName());
                companyVos.add(companyVo);
            }
        }

        //对companyVo 排序
        if(type.equals("foundTime")){ //根据时间
            if(order.equals("asc")) { //升序
                companyVos.sort(new Comparator<CompanyVo>() {
                    @Override
                    public int compare(CompanyVo o1, CompanyVo o2) {
                        Date time1 = o1.getFoundTime();
                        Date time2 = o2.getFoundTime();
                        return  time1.compareTo(time2);
                    }
                });
            } else if(order.equals("desc")) { //降序
                companyVos.sort(new Comparator<CompanyVo>() {
                    @Override
                    public int compare(CompanyVo o1, CompanyVo o2) {
                        Date time1 = o1.getFoundTime();
                        Date time2 = o2.getFoundTime();
                        return time2.compareTo(time1);
                    }
                });
            }
        } else if(type.equals("point")) { //根据综合评分
            if(order.equals("asc")) { //升序
                companyVos.sort(new Comparator<CompanyVo>() {
                    @Override
                    public int compare(CompanyVo o1, CompanyVo o2) {
                        int point1 = o1.getPoint();
                        int point2 = o2.getPoint();
                        return  point1 - point2;
                    }
                });
            } else if(order.equals("desc")) { //降序
                companyVos.sort(new Comparator<CompanyVo>() {
                    @Override
                    public int compare(CompanyVo o1, CompanyVo o2) {
                        int point1 = o1.getPoint();
                        int point2 = o2.getPoint();
                        return  point2 - point1;
                    }
                });
            }

        } else { //根据估值
            if(order.equals("asc")) { //升序
                companyVos.sort(new Comparator<CompanyVo>() {
                    @Override
                    public int compare(CompanyVo o1, CompanyVo o2) {
                        float vluations1 = o1.getValuations();
                        float vluations2 = o2.getValuations();
                        return  (int)vluations1 - (int)vluations2;
                    }
                });
            } else { //降序
                companyVos.sort(new Comparator<CompanyVo>() {
                    @Override
                    public int compare(CompanyVo o1, CompanyVo o2) {
                        float f1 = o1.getValuations();
                        float f2 = o2.getValuations();
                        return  (int)f2 - (int)f1;
                    }
                });
            }
        }

        //手工分页
        List<CompanyVo> companyVoList0= new ArrayList<>();
        companyVoList0 = pageBySubList(companyVos, (int)pageable.getPageSize(), (int)pageable.getPageNumber());
        companyListVo.setTotalCount(companyVos.size());
        companyListVo.setList(companyVoList0);

        return companyListVo;

    }
    public static List<CompanyVo> pageBySubList(List<CompanyVo> list, int pagesize, int curPage) {
        int currentPage = curPage+1;
        List<CompanyVo> subList =new ArrayList<>();
        int size=list.size();
        int pageStart = currentPage==1 ? 0 : (currentPage-1) * pagesize;
        int pageEnd = size < currentPage*pagesize ? size : currentPage*pagesize;
        if(size >  pageStart) {
            subList = list.subList(pageStart, pageEnd);
        }
        return subList;
    }


    @Override
    public CompanyListVo getCompanyListsByTrade(String tradeId, String tradeType) {
        CompanyListVo companyListVo = new CompanyListVo();

        List<CompanyTradeEntity> companyTradeEntityList = null;
        if (tradeType.equals("TRADEB")) {
            companyTradeEntityList = companyTradeRepository.findByTradeB(tradeId);
        } else if (tradeType.equals("TRADEC")) {
            companyTradeEntityList = companyTradeRepository.findByTradeC(tradeId);
        }

        if (companyTradeEntityList == null){
            return companyListVo;
        } else {
            List<CompanyVo> companyVos = new ArrayList<>();

            for (CompanyTradeEntity companyTradeEntity : companyTradeEntityList) {
                CompanyEntity companyEntity = companyRepository.findOne(companyTradeEntity.getCompanyId());
                CompanyVo companyVo = new CompanyVo();
                String companyId = companyEntity.getId();
                companyVo = getCompanyById(companyId);
                companyVos.add(companyVo);
            }
            companyListVo.setTotalCount(companyTradeEntityList.size());
            companyListVo.setList(companyVos);
        }
        return companyListVo;
    }

    @Override
    public void addCompany(CompanyAddVo companyAddVo) {
        CompanyEntity companyEntity = new CompanyEntity();
        companyEntity.setId(UUIDUtils.getUUID());
        companyEntity.setCreateTime(new Date());
        companyEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(companyAddVo, companyEntity);
        PeopleEntity peopleEntity = peopleRepository.findByName(companyAddVo.getCorporate());
        if (peopleEntity == null) {
            peopleEntity = new PeopleEntity();
            peopleEntity.setId(UUIDUtils.getUUID());
            peopleEntity.setUpdateTime(new Date());
            peopleEntity.setCreateTime(new Date());
            peopleEntity.setName(companyAddVo.getCorporate());
            peopleRepository.save(peopleEntity);
        }
        companyEntity.setCorporateId(peopleEntity.getId());
        companyRepository.save(companyEntity);


    }

    @Transactional
    @Override
    public void del(DelBody id) {
        companyRepository.delete(id.getId());
        List<CompanyFinancingEntity> companyFinancingEntityList;

        // 删除融资信息
        companyFinancingEntityList = companyFinancingRepository.findByCompanyId(id.getId());
        for (CompanyFinancingEntity companyFinancingEntity : companyFinancingEntityList) {
            DelBody body = new DelBody();
            body.setId(companyFinancingEntity.getId());
            companyFinancingService.del(body);
        }

        // 对外投资
        List<CompanyInvesterEntity> companyInvesterEntityList = companyInvesterRepository.findByCompanyId(id.getId());
        for (CompanyInvesterEntity companyInvesterEntity : companyInvesterEntityList) {
            DelBody body = new DelBody();
            body.setId(companyInvesterEntity.getId());
            companyInvesterService.del(body);
        }

        // 竞争对手
        companyOpponentRepository.deleteByCompanyId(id.getId());

        companyPointRepository.deleteByCompanyId(id.getId());

        companyReportRepository.deleteByCompanyId(id.getId());

        companyStockholderRepository.deleteByCompanyId(id.getId());

        companyTeamRepository.deleteByCompanyId(id.getId());

        companyTradeRepository.deleteByCompanyId(id.getId());

        institutionCompanyRepository.deleteByCompanyId(id.getId());
    }

    @Transactional
    @Override
    public void delList(DelListBody idList) {
        for(String id : idList.getList()) {
            DelBody body = new DelBody();
            body.setId(id);
            del(body);
        }
    }

    @Override
    public void modify(CompanyModVo companyModVo){
        CompanyEntity companyEntity = companyRepository.findOne(companyModVo.getId());

        if (companyEntity == null) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "没有对应信息");
        }
        companyEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(companyModVo, companyEntity);
        companyRepository.save(companyEntity);
    }

    @Override
    public int getCompanyCounByTrade(String tradeId, String tradeType) {
        List<CompanyTradeEntity> companyTradeEntityList = new ArrayList<>();
        if (tradeType.equals("TRADEB")) {
            companyTradeEntityList = companyTradeRepository.findByTradeB(tradeId);
        } else if (tradeType.equals("TRADEC")) {
            companyTradeEntityList = companyTradeRepository.findByTradeC(tradeId);
        }
//        else if (tradeType.equals("TRADED")) {
//            companyTradeEntityList = companyTradeRepository.findByTradeD(tradeId);
//        }
        return companyTradeEntityList.size();
    }

    @Override
    public float getFinicingByTrade(String tradeId, String tradeType) {

        float financing = 0;

        List<CompanyTradeEntity> companyTradeEntityList = new ArrayList<>();
        if (tradeType.equals("TRADEB")) {
            companyTradeEntityList = companyTradeRepository.findByTradeB(tradeId);
        } else if (tradeType.equals("TRADEC")) {
            companyTradeEntityList = companyTradeRepository.findByTradeC(tradeId);
        }
//        else if (tradeType.equals("TRADED")) {
//            companyTradeEntityList = companyTradeRepository.findByTradeD(tradeId);
//        }

        for (CompanyTradeEntity companyTradeEntity : companyTradeEntityList) {
            financing += companyFinancingService.getCompanyFinanceThisYear(companyTradeEntity.getCompanyId());
        }
        return financing;
    }

    @Override
    public float getAluationsLisByTradeId(String tradeId, String tradeType) {

        float valuations = 0;

        List<CompanyTradeEntity> companyTradeEntityList = new ArrayList<>();
        if (tradeType.equals("TRADEB")) {
            companyTradeEntityList = companyTradeRepository.findByTradeB(tradeId);
        } else if (tradeType.equals("TRADEC")) {
            companyTradeEntityList = companyTradeRepository.findByTradeC(tradeId);
        }
//        else if (tradeType.equals("TRADED")) {
//            companyTradeEntityList = companyTradeRepository.findByTradeD(tradeId);
//        }

        for (CompanyTradeEntity companyTradeEntity : companyTradeEntityList) {
            CompanyEntity companyEntity = companyRepository.findOne(companyTradeEntity.getCompanyId());
            valuations += companyEntity.getValuations();
        }
        return valuations;
    }

    @Override
    public CompanyTradeListVo getCompanyTradeList(String companyId) {
        CompanyTradeListVo companyTradeListVo = new CompanyTradeListVo();
        List<CompanyTradeEntity> companyTradeEntities = new ArrayList<>();
        companyTradeEntities= companyTradeRepository.findByCompanyId(companyId);
        companyTradeListVo.setTotalCount(companyTradeEntities.size());
        companyTradeListVo.setList(companyTradeEntities);
        return companyTradeListVo;
    }

    @Override
    public String getCompanyId(String fullname) {
        CompanyEntity companyEntity = companyRepository.findByFullName(fullname);
        return companyEntity.getId();
    }
}
